<template>
	<view class="box">
		<!-- index.wxml -->
		<view class="top">
			<image class="img" src="@/images/icon_ble.png" mode=""></image>
			<button class="t-btn" @click="chooseBluetooth">请选择蓝牙设备</button>
		</view>
		<view class="lyaName">
			<view class="l">
				已选择蓝牙:
			</view>
			<view class="r">
				{{currentDevice['name'] || '未选择'}}
			</view>
		</view>


		<view class="select">
			<button class="l" @tap="createBLEConnection">
				<u-icon name="wifi" color="#2979ff" size="40rpx"></u-icon>
				链接
			</button>

			<button class="r" @click="closeBLEConnection">
				<u-icon name="wifi-off" color="red" size="40rpx"></u-icon>
				断开
			</button>
		</view>
		<button class="pushTsp" @tap="toTsplPrinter">打印</button>
		<!-- <page-container :show="showBleSearchPop" :round="true" :overlay="true" position="bottom" @beforeleave="closeBleSearch"> -->
		<u-popup :show="showBleSearchPop" :round="20" @close="closeBleSearch" mode="bottom">
			<view class="search-ble-page">
				<view class="head">
					<view class="title">BLE</view>
					<view v-if="currentDevice && connected" class="sub-title">已配对</view>
				</view>
				<scroll-view class="list-view" scroll-y scroll-with-animation>
					<ble-list-view :list="bleDeviceList" @onSelect="chooseDevice"></ble-list-view>
				</scroll-view>
				<view class="button">
					<ble-button v-if="discovering" :disabled="true">搜索中...</ble-button>
					<!-- reSearchBleDevices -->
					<ble-button v-else @tap.native="startBluetoothDevicesDiscoveryFun">搜索</ble-button>
				</view>
			</view>
		</u-popup>
		<!-- </page-container> -->

	</view>
</template>

<script>
	import bleButton from '@/components/button';
	import blePanel from '@/components/panel';
	import bleListView from '@/components/listView';
	import bleIcon from '@/components/icon';
	// index.js
	const {
		LAST_CONNECTED_DEVICE
	} = require('../../utils/constant.js');
	const {
		inArray
	} = require('../../utils/util.js');

	// 定时器
	var interval;
	export default {
		components: {
			bleButton,
			blePanel,
			bleListView,
			bleIcon
		},
		data() {
			return {
				showBleSearchPop: false,
				discovering: false,
				connected: false,
				bleDeviceList: [],
				currentDevice: {},
				bluetoothOpen: false
			};
		},
		onLoad() {},
		onUnload() {
			// this.closeBluetoothAdapter();
		},
		methods: {
			toTsplPrinter(event, _dataset) {

				if (!this.connected) {
					uni.showModal({
						title: '',
						content: '请先连接蓝牙设备!',
						showCancel: false
					});
					return;
				}
				uni.navigateTo({
					url: '/pages/lanya/index'
				});
			},
			// 停止搜索蓝牙设备
			closeBleSearch() {
				clearTimeout(interval);
				this.stopBluetoothDevicesDiscoveryFun();
			},
			getBLEDeviceCharacteristicsFun(deviceId, serviceId) {
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						console.log('getBLEDeviceCharacteristics success', res.characteristics);
						// 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
						// 只能一个个去试
						for (let i = 0; i < res.characteristics.length; i++) {
							const item = res.characteristics[i];
							let device = {}
							if (item.properties.write) {
								device = Object.assign(this.currentDevice, {
									serviceId: serviceId,
									characteristicId: item.uuid
								});
								this.connected = true,
									this.currentDevice = device
								uni.setStorageSync(LAST_CONNECTED_DEVICE, device);
								this.$nextTick(() => {
									console.log('currentDevice changed:', this.currentDevice);
								});
								break;
							}
							// if(item.properties.notify){
							// 	device=Object.assign(device,{notify:item.uuid})
							// 	uni.setStorageSync(LAST_CONNECTED_DEVICE, device);
							// }
						}
					},
					fail(res) {
						console.error('getBLEDeviceCharacteristics', res);
					}
				});
			},
			// 获取蓝牙低功耗设备所有服务 (service)
			getBLEDeviceServicesFun(deviceId) {
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log('getBLEDeviceServices', res);
						for (let i = 0; i < res.services.length; i++) {
							if (res.services[i].isPrimary) {
								this.getBLEDeviceCharacteristicsFun(deviceId, res.services[i].uuid);
								return;
							}
						}
					}
				});
			},
			// 关闭蓝牙连接
			closeBluetoothAdapter() {
				uni.closeBluetoothAdapter();
				this.discovering = false,
					this.bluetoothOpen = false
			},
			// 点击选中某个蓝牙设备
			chooseDevice(event) {
				const device = event.detail;
				console.log('chooseDevice: ', device);
				this.currentDevice = device || null
				this.showBleSearchPop = false
				this.connected = false

			},
			// 主动停止搜索蓝牙设备
			stopBluetoothDevicesDiscoveryFun() {
				uni.stopBluetoothDevicesDiscovery({
					complete: () => {
						console.log('stopBluetoothDevicesDiscovery.');
						this.discovering = false

					}
				});
			},
			// 找到蓝牙设备 回调
			onBluetoothDeviceFoundFun() {
				uni.onBluetoothDeviceFound((res) => {
					res.devices.forEach((device) => {
						if (!device.name && !device.localName) {
							return;
						}
						const foundDevices = this.bleDeviceList;
						const idx = inArray(foundDevices, 'deviceId', device.deviceId);
						const data = {};
						if (idx === -1) {
							data[`bleDeviceList[${foundDevices.length}]`] = device;
							this.bleDeviceList.push(device)
						} else {
							data[`bleDeviceList[${idx}]`] = device;
							this.bleDeviceList.push(device)
						}
						// this.setData(data);
						// this.bleDeviceList=data
						console.log(data, 'data');
					});
				});
			},
			// 选择蓝牙设备
			chooseBluetooth() {
				// this.bleDeviceList = []
				this.showBleSearchPop = true
				// 开始搜索蓝牙设备
				this.searchBleDevicesFun();
			},
			// 搜索蓝牙设备
			// 从打开蓝牙适配器开始
			searchBleDevicesFun() {
				// if (!uni.openBluetoothAdapter) {
				//     uni.showModal({
				//         title: '提示',
				//         content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
				//     });
				//     return;
				// }
				if (this.bluetoothOpen) {
					// 蓝牙适配器已经打开
					console.log('蓝牙适配器已打开，开始搜索蓝牙设备...');
					this.startBluetoothDevicesDiscoveryFun();
					return;
				}

				// 打开蓝牙适配器 搜索蓝牙设备
				// 后续蓝牙操作依赖适配器
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log('openBluetoothAdapter success', res);
						this.bluetoothOpen = true

						this.startBluetoothDevicesDiscoveryFun();
					},
					fail: (res) => {
						console.log('openBluetoothAdapter fail', res);
						if (res.errCode === 10001) {
							uni.showModal({
								title: '错误',
								content: '未找到蓝牙设备, 请打开蓝牙后重试。',
								showCancel: false
							});
							uni.onBluetoothAdapterStateChange((res) => {
								console.log('onBluetoothAdapterStateChange', res);
								if (res.available) {
									// 取消监听，否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange，
									// 导致再次调用_startBluetoothDevicesDiscovery
									uni.onBluetoothAdapterStateChange(() => {});
									this.startBluetoothDevicesDiscoveryFun();
								}
							});
						}
					}
				});
				uni.onBLEConnectionStateChange((res) => {
					// 该方法回调中可以用于处理连接意外断开等异常情况
					console.log('onBLEConnectionStateChange',
						`device ${res.deviceId} state has changed, connected: ${res.connected}`);
					if (this.connected && !res.connected) {
						uni.showToast({
							title: '蓝牙连接已断开',
							duration: 1200
						});
					}
					if (this.connected !== res.connected) {
						this.connected = res.connected

					}
				});
			},

			// 开始搜索蓝牙设备
			startBluetoothDevicesDiscoveryFun() {
				if (this.discovering) {
					return;
				}
				this.discovering = true
				// 12s 之后停止搜索
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('_startBluetoothDevicesDiscovery success', res);
						this.onBluetoothDeviceFoundFun();
						interval = setTimeout(() => {
							console.log('搜索超过12s，停止搜索');
							this.stopBluetoothDevicesDiscoveryFun();
						}, 12000);
					},
					fail: (res) => {
						console.log('_startBluetoothDevicesDiscovery fail', res);
					}
				});
			},
			// 根据 deviceId 和 name 连接蓝牙设备
			createBLEConnectionFun(device) {
				console.log(device, 'device');
				const deviceId = device.deviceId;
				uni.showLoading({
					title: '连接中...',
					mask: true
				});
				uni.createBLEConnection({
					deviceId,
					success: () => {
						console.log('createBLEConnection success');
						this.getBLEDeviceServicesFun(deviceId);
						uni.hideLoading();
						uni.showToast({
							title: '连接成功',
							icon: 'none',
							duration: 1200
						});
					},
					fail: (res) => {
						uni.hideLoading();
						if (res.errno === 1509007) {
							// 已连接
							uni.showToast({
								title: '已连接',
								icon: 'none',
								duration: 1200
							});
						} else {
							uni.showToast({
								title: '连接失败',
								icon: 'none',
								duration: 1200
							});
						}
						console.log('createBLEConnection fail', res);
					}
				});
			},
			// 连接蓝牙设备
			createBLEConnection(e) {
				if (!this.currentDevice) {
					uni.showToast({
						title: '请选择蓝牙设备',
						icon: 'none',
						duration: 1000
					});
					return;
				}
				if (!this.bluetoothOpen) {
					// 连接的时候需要判断蓝牙适配器是否初始化
					// 打开蓝牙适配器 搜索蓝牙设备
					// 后续蓝牙操作依赖适配器
					uni.openBluetoothAdapter({
						success: (res) => {
							console.log('openBluetoothAdapter success', res);
							this.bluetoothOpen = true

							this.createBLEConnectionFun(this.currentDevice);
						},
						fail: (res) => {
							uni.showToast({
								title: '打开蓝牙失败，请检查后重试',
								icon: 'none',
								duration: 1000
							});
							return;
						}
					});
				} else {
					this.createBLEConnectionFun(this.currentDevice);
				}
			},
			// 断开蓝牙连接
			closeBLEConnectionFun() {
				uni.closeBLEConnection({
					deviceId: this.currentDevice.deviceId
				});
				this.connected = false

			},
			// 断开蓝牙连接
			closeBLEConnection(e) {
				console.log('currentDevice', this.currentDevice);
				if (!this.currentDevice) {
					uni.showToast({
						title: '当前没有连接蓝牙设备',
						icon: 'none',
						duration: 1200
					});
					return;
				}
				this.closeBLEConnectionFun(this.currentDevice);
			},
		},
	};
</script>
<style scoped lang="scss">
	.box {
		width: 100vw;
		height: 100vh;
		padding: 40rpx;
		box-sizing: border-box;
		background-color: #eee;

		.pushTsp {
			position: fixed;
			left: 50%;
			transform: translateX(-50%);
			bottom: 200rpx;
			width: 80%;
			height: 80rpx;
			color: #fff;
			background-color: #4588fa;
			padding: 0;
			text-align: center;
			line-height: 80rpx;
		}

		.select {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 32rpx;

			>button {
				padding: 0;
				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.l {
				color: #4588fa;
			}

			.r {
				color: red;
			}

		}

		.lyaName {
			display: flex;
			align-items: center;
			font-size: 30rpx;
			color: #000;
			margin: 20rpx;

			.r {
				color: #4588fa;
			}
		}

		.top {
			width: 100%;
			height: 100rpx;
			box-sizing: border-box;
			position: relative;
			margin-top: 60rpx;

			.img {
				width: 140rpx;
				height: 140rpx;
				position: absolute;
				left: 50%;
				top: -85rpx;
				transform: translateX(-50%);
				// background-color: #fff;
				z-index: 99;
			}

			.t-btn {
				width: 100%;
				height: 80rpx;
				position: absolute;
				top: 20rpx;
				box-sizing: border-box;
				border-radius: 10rpx;
				background-color: #4588fa;
				font-size: 28rpx;
				color: #fff;
				line-height: 80rpx;
				text-align: center;
			}
		}

		.search-ble-page {
			height: 62vh;
			padding: 40rpx 30rpx;
			display: flex;
			flex-direction: column;
		}

		.search-ble-page .head {
			/* height: 80rpx; */
		}

		.search-ble-page .title {
			font-size: 34rpx;
			font-weight: 600;
		}

		.search-ble-page .sub-title {
			font-size: 24rpx;
			color: #585a59;
		}

		.search-ble-page .list-view {
			margin: 41rpx 0;
			flex: 1;
			overflow: auto;
			background: #f7f7f7;
		}

		.search-ble-page .button {
			height: 82rpx;
		}

	}
</style>